package com.umiwe.permission.service.impl;


import com.umiwe.entity.UmiweRole;
import com.umiwe.entity.UmiweRolePermission;
import com.umiwe.permission.mapper.RoleMapper;
import com.umiwe.permission.mapper.RolePermissionMapper;
import com.umiwe.permission.service.RoleService;
import com.umiwe.utils.Result;
import com.umiwe.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    /**
     * 查询所有的角色信息
     * @return
     */
    @Override
    public List<UmiweRole> getlist() {
        return roleMapper.selectList(null);
    }

    /**
     *
     * 修改角色自身信息以及角色和权限关系数据
     *
     * @param role
     * @param
     * @return
     */
    @Override
    public Result updateRole(UmiweRole role,  UmiweRolePermission permissionId) {
        //1.参数校验
        if(role==null)
            throw new IllegalArgumentException("保存对象不能为空");
        if(StringUtils.isEmpty(role.getName()))
            throw new IllegalArgumentException("角色名不能为空");
        //2.更新角色自身信息
        int rows=roleMapper.updateById(role);
        if(rows==0)
            Result.error(ResultCode.RECORD_NULL);
        rolePermissionMapper.deleteRolePer("role_id",role.getId());
        //3.2添加新的关系数据
        rolePermissionMapper.insertRolePer(role.getId(), permissionId);
        //4.返回结果
        return Result.success(rows);
    }
    /**
     * 保存角色自身信息以及角色和权限关系数据
     * @param role
     * @param permissionId
     * @return
     */
    @Override
    public Result insertRole(UmiweRole role, Integer[] permissionId) {
        //1.参数校验
        if(role==null)
            throw new IllegalArgumentException("保存对象不能为空");
        if(StringUtils.isEmpty(role.getName()))
            throw new IllegalArgumentException("角色名不能为空");
        //2.保存角色自身信息
        int rows=roleMapper.insert(role);
        //3.保存角色权限关系数据
        //rolePermissionMapper.insertRolePer(role.getId(), permissionId);
        //4.返回结果
        return Result.success(rows);
    }

    /**
     * 删除角色信息以及角色和权限关系数据
     * @param role
     * @return
     */
    @Override
    @Transactional
    public Result deleteRole(UmiweRole role) {
        if(role.getId()==null)
            throw  new IllegalArgumentException("没有此角色");
        rolePermissionMapper.deleteRolePer("role_id",role.getId());
        int rows = roleMapper.deleteById(role);
        return Result.success(rows);
    }
}
